/*
 * @Author: Yuluo 568055454@qq.com
 * @Date: 2023年06月18日 07:28:15
 * @LastEditors: Yuluo 568055454@qq.com
 * @LastEditTime: 2023年07月16日 03:37:47
 * @FilePath: \Mood-Blog-System\back\util\db\index.js
 * @Description:  数据库事务处理模块，提供事务处理函数transaction和自动事务处理函数autoTransaction，
 *                用于处理数据库事务，防止数据不一致性问题
 * Copyright (c) 2023 by Yuluo, All Rights Reserved. 
 */
const mongoose = require('mongoose');
const { logTemplate } = require('../log4js');
const logger = require('../../log4');
/**
 * @description: 事务处理 需要手动commit或rollback
 * @param {Function} callback
 * @return {Promise}
 */
function transaction(callback) {
    if (!callback || typeof callback !== 'function')
        throw new Error('transaction: callback is not a function');
    return new Promise(async (resolve, reject) => {
        try {
            await callback(sission);
        } catch (error) {
            logger('db').error(
                logTemplate({ title: '事务处理失败，数据回滚', message: error.message, data: error })
            );
            await session.abortTransaction();
            reject(t);
        } finally {
            session.endSession();
        }
    });
}

function autoTransaction(callback) {
    if (!callback || typeof callback !== 'function')
        throw new Error('autoTransaction: callback is not a function');

    return new Promise(async (resolve, reject) => {
        const session = await mongoose.startSession();
        await session.startTransaction();
        try {
            const result = await callback(session);
            await session.commitTransaction();
            resolve(result);
        } catch (error) {
            logger('db').error(
                logTemplate.bind(this)({ title: '自动事务处理失败，数据回滚', message: error.message, data: error })
            );
            await session.abortTransaction();
            reject(error);
        } finally {
            if (session) await session.endSession();
        }
    });
}

module.exports = {
    transaction,
    autoTransaction
}